<?php

declare(strict_types=1);

namespace app\model;

use app\model\base\BaseCouponProductModel;
use app\Query;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $name 权益产品
 * @property int $brand_id 品牌
 * @property int $status 状态(1:启用,0:关闭)
 * @property int $sort 排序
 * @property string $created_at
 * @property string $updated_at
 * @property string $mark 第一次导入聚推客使用匹配，上线后可删除
 * @property-read \app\model\CouponProductChannel $coupon_product_channel
 * @property-read \app\model\CouponProductChannel $couponProductChannel
 * @property-read \app\model\CouponCate[] $coupon_cate
 * @property string $profit 预计佣金
 * @property-read \app\model\CouponOrder[] $coupon_order
 * @property int $type_id 关联品牌分类表id
 * @property string $delete_time 删除时间
 * @property string $type 所属供应商
 * @property-read \app\model\CouponBrandType $brand_type
 * @property-read \app\model\CouponBrandType $coupon_brand_type
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class CouponProduct extends BaseCouponProductModel
{
    use SoftDelete;
    const STATUS_ACTIVE = 1; //激活
    const STATUS_CLOSE = 0; //关闭

    const TYPE_JTK = 'jutuike';  //聚推客
    const TYPE_QY = 'quanyi';    //权益


    protected $deleteTime = 'delete_time';

    //商品列表
    public static function goodsList($params)
    {
        $key = $params['key'] ?? '';
        $supplierId = $params['supplierId'] ?? '';
        $list = self::when($key, function ($query) use ($key) {
               $query->where('coupon_product.name|coupon_product.id', 'like', '%' . $key . "%");
           })->with(["couponProductChannel"=>function($query) use ($supplierId){
                  $query->when($supplierId, function ($query) use ($supplierId) {
                           $query->where("coupon_product_channel.supplier_id",$supplierId);
                  });
          }, "couponCate"])->withCount("couponOrder",false)
            ->when($supplierId, function ($query) use ($supplierId) {
                $query->alias("CouponProduct")->hasWhere("couponProductChannel", ['supplier_id' => $supplierId]);
            })->paginate();
        return $list;
    }

    //面额列表
    public function productList($params)
    {
        $map = array();
        $map[] = ['type', '=', self::TYPE_QY];
        if (isset($params['type_id']) && !empty($params['type_id'])) {
            $map[] = ['type_id', '=', $params['type_id']];
        }
        if (isset($params['id']) && !empty($params['id'])) {
            $map[] = ['id', '=', $params['id']];
        }
        if (isset($params['name']) && !empty(trim($params['name']))) {
            $map[] = ['name', 'like',  '%'. trim($params['name']) . '%'];
        }
        return self::where($map)->field('id, name, sort, updated_at, status, type_id')
            ->with(['coupon_product_channel' => function($query) {
                $query->where('type', '<>', self::TYPE_JTK)->withOutField('extend, rule, deleted_at, type, mark');
            }])->order('created_at desc')->paginate()->toArray();
    }


    public function couponProductChannel()
    {
        return $this->hasMany(CouponProductChannel::class, "product_id", "id")->with('base_supplier');
    }

    /**
     * 一对一关联关系
     * 属于品牌
     */
    public function brandType()
    {
        return $this->belongsTo(CouponBrandType::class, 'type_id', 'id')->with('brand');
    }

    public function couponBrandType()
    {
        return $this->belongsTo(CouponBrandType::class, 'type_id', 'id');
    }

    public function couponCate()
    {
        return $this->belongsToMany(CouponCate::class, 'coupon_brand_cate_relation', 'cate_id', 'brand_id');
    }

    public function couponOrder()
    {
        return $this->belongsToMany(CouponOrder::class, 'goods_cart', 'order_id', 'goods_id');
    }

    /**
     * 判断是否已经存在
     * @param int $type_id
     * @param string $name
     * @return bool
     */
    public function checkExists(int $type_id, string $name)
    {
        return self::where('type_id', $type_id)->where('name', $name)->findOrEmpty();
    }

    /**
     * 判断排序是否已存在
     * @param int $sort
     * @return bool|
     */
    public function checkIsExistsSort($type_id, $sort)
    {
        return self::where('type_id', $type_id)->where('sort', $sort)->findOrEmpty();
//        $info = self::where('type_id', $type_id)->where('sort', $sort)->findOrEmpty();
//        if (!$info->isEmpty()) {
//            return ['sort' => (int)self::max('sort')+1, 'id' => $info->id];
//        }
//        return ['sort' => $sort, 'id' => ''];
    }

    //代理端会员卡券商品管理
    public function getList($param)
    {
        $key = isset($param['key'])?trim($param['key']):'';
        $list = self::query()
            ->alias('CouponProduct')
            ->where('status', self::STATUS_ACTIVE)->field('id, name, type_id')
            ->where('type', self::TYPE_QY)
            ->with(['couponProductChannel' => function($query) use($key) {
                $query->availableSale()
                    ->when($key, function ($query) use($key) {
                        $query->where('id|name', 'like', '%'.$key.'%');
                    })->order('cost_price asc')
                    ->field('id, name, origin_id, product_id, cost_price, market_price, brand_id')
                    ->withLimit(1)//取最便宜的一个产品
                    ->with(['brand' => function($query) {
                        $query->field('id, name');
                    }]);
            }])
            ->where(function ($query) use($key){
                /**
                 * @var Query $query
                 */
                $query->whereRaw('EXISTS(
                SELECT * FROM coupon_product_channel WHERE product_id = `CouponProduct`.`id`
                    and `status` = ' . CouponProductChannel::STATUS_ACTIVE . '
                    and butt = ' . CouponProductChannel::BUTT_ACTIVE . '
                    and sku_type = ' . CouponProductChannel::SKU_TYPE_ZC . '
                    and relate_state = ' . CouponProductChannel::RELETE_STATE_YPP . '
                    and shelf_state = ' . CouponProductChannel::RELETE_STATE_YPP . '
                    and (name like "%' .$key. '%" OR id like "%' .$key. '%")
                    )'
                );
            })
            ->paginate();
        return success('success', $list);
    }
}
